package app.tasks;

import app.env.Data;
import app.agent.Schedule;
import app.agent.TargetAgent;
import app.env.ShowGui;
import app.util.AppUtils;
import framework.task.Task;
import jade.core.AID;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @Name: DetectEmit
 * @Description:
 * @Author: colfish
 * @Date: 2021/5/14 9:03
 * 好好学习，天天向上！
 */
public class DetectEmit extends Task {
    private static final long serialVersionUID = 8997533332118738523L;

    private final Logger logger = LogManager.getLogger(Task.class);

    public DetectEmit(){
        super();
        behaviour = new SelfBehaviour();
    }

    private class SelfBehaviour extends SimpleBehaviour {
        private static final long serialVersionUID = -317065722874315928L;
        private boolean end = false;
        @Override
        public void action() {
            TargetAgent targetAgent = (TargetAgent) myAgent;
            // 探测是否被包围，如果被包围，清理周围信号，完成后向管理员代理发送清理完成的消息，否则刷新辐射区域
            if(AppUtils.isSurrounded(targetAgent.getPosition())) {
                // 1. 清理周围信号
                targetAgent.clearSignal();
                // 2. 向管理员代理发送已经清理完毕的信号
                ACLMessage signalMessage =new ACLMessage(ACLMessage.INFORM);
                AID receiver = Schedule.IDENTIFIER;
                signalMessage.addReceiver(receiver);
                signalMessage.setContent(Data.CLEAR_FINISHED);
                targetAgent.send(signalMessage);
                ShowGui.board[targetAgent.getPosition().x][targetAgent.getPosition().y] = Data.TARGET_STOP_SIGNAL;
                logger.info(AppUtils.logMessage(targetAgent.getAID(), receiver, signalMessage));
                // End()
                end = true;
            }else
                targetAgent.initSignal();
        }

        public boolean done(){
            if(end){
                System.out.println("STime:" + Data.Stime);
                System.out.println("Scnt:" + Data.Scnt);
                System.out.println("FTime:" + Data.Ftime);
                System.out.println("Fcnt:" + Data.Fcnt);
                logger.info("TargetAgent: <" + myAgent.getLocalName() +"> End Task...");
            }
            return end;
        }
    }
}
